package com.example.drugs1.services;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.drugs1.dao.UserAccountRepository;
import com.example.drugs1.entities.User;
import com.example.drugs1.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;

@Service("userDetailsService")
public class UserAccountService implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAccountRepository userAccountRepository;
    @Override
    public UserDetails loadUserByUsername(@RequestParam("username") String username) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper=new QueryWrapper();
        wrapper.eq("user_name",username);
        User user =userMapper.selectOne(wrapper);
        if(user ==null){
        }
        List<GrantedAuthority> auths= AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRole());
        return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getPassword(),auths);
    }

    public int UpdateUser( String username, String password,String password1){
        QueryWrapper<User> wrapper=new QueryWrapper();
        wrapper.eq("user_name",username);
        User user =userMapper.selectOne(wrapper);
        if(user!=null){
            //matches(原密码，新密码)用于密码匹配，可用于修改密码
            if(bCryptPasswordEncoder.matches(password,user.getPassword())){
                if (password1.equals("")){
                    return 3;
                }else {
                    user.setPassword(bCryptPasswordEncoder.encode(password1));
                    userAccountRepository.save(user);
                }
                return 2;
            }else {

                return 1;
            }
        }else {
            return 0;
        }
    }
}
